export enum ApiResponseCode {
    SUCCESS = 200, // 成功
    ERROR = 500, // 服务器错误
    ILLEGAL_INPUT = 400, // 非法输入
    UNAUTHORIZED = 401, // 未授权
    FORBIDDEN = 403, // 禁止访问
    NOT_FOUND = 404 // 未找到
}

interface ApiResponse {
    code: ApiResponseCode;
    result: 'success' | 'error';
    message: string;
    data: any;
}

// 成功
export function sucessResponse(data: any, message: string = '成功'): ApiResponse {
    return {
        code: ApiResponseCode.SUCCESS,
        result: 'success',
        message: message,
        data: data
    }
}

// 服务器错误
export function errorResponse(message: string = '失败'): ApiResponse {
    return {
        code: ApiResponseCode.ERROR,
        result: 'error',
        message: message,
        data: null
    }
}

// 异常捕获错误
export function catchErrorResponse(error: any): ApiResponse {
    let message = error;
    if (Array.isArray(error?.errors) && error.errors.length > 0) {
        message = error.errors[0].message
    } else if (typeof error === 'object' && error !== null) {
        message = error.message
    }
    return {
        code: ApiResponseCode.ERROR,
        result: 'error',
        message: message,
        data: null
    }
}

// 非法输入
export function illegalInputResponse(message: string = '非法输入'): ApiResponse {
    return {
        code: ApiResponseCode.ILLEGAL_INPUT,
        result: 'error',
        message: message,
        data: null
    }
}

// 未授权
export function unauthorizedResponse(message: string = '未授权'): ApiResponse {
    return {
        code: ApiResponseCode.UNAUTHORIZED,
        result: 'error',
        message: message,
        data: null
    }
}

// 禁止访问
export function forbiddenResponse(message: string = '禁止访问'): ApiResponse {
    return {
        code: ApiResponseCode.FORBIDDEN,
        result: 'error',
        message: message,
        data: null
    }
}

// 未找到
export function notFoundResponse(message: string = '未找到'): ApiResponse {
    return {
        code: ApiResponseCode.NOT_FOUND,
        result: 'error',
        message: message,
        data: null
    }
}


